package com.woniu.interceptor;


import com.woniu.annotation.CheckPermission;
import com.woniu.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: Gwj
 * @Date: 2024/6/26 17:06
 */
@Slf4j
public class PermissionInterceptor implements HandlerInterceptor {

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // handler 代表正要执行的对象
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            // 判断是否有指定的权限
            boolean f = method.hasMethodAnnotation(CheckPermission.class);
            if (f) {
                //1.得到注解上的权限的值
                CheckPermission checkPermission = method.getMethodAnnotation(CheckPermission.class);
                String value = checkPermission.value();
                System.out.println(method.getMethod().getName() + ":这个方法需要的权限是:" + value);
                //2.判断当前用户是否有这个权限
                //得到用户名
                String token = request.getHeader("authentication");
                String accountName = jwtUtil.parseToken(token);
                log.info("================================"+accountName);
                //因为登录的时候,就缓存了权限数据，所以我们只要从redis里面获取权限数据
                Boolean b = stringRedisTemplate.opsForSet().isMember("permission" + accountName, value);
                if (b) {
                    return true;
                } else {
                    throw new RuntimeException("对不起权限不足！需要：<" + value + ">权限");
                }
            } else {
                return true;
            }
        }
        return true;
    }
}
